package cn.wenhe9.hefengweather.ui.place

import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import cn.wenhe9.hefengweather.MainActivity
import cn.wenhe9.hefengweather.R
import cn.wenhe9.hefengweather.logic.model.Location
import cn.wenhe9.hefengweather.logic.model.Place
import cn.wenhe9.hefengweather.ui.weather.WeatherActivity

/**
 *@author DuJinliang
 *2021/10/1
 */
class PlaceAdapter(private val fragment : PlaceFragment, private val placeList : List<Location>) : RecyclerView.Adapter<PlaceAdapter.ViewHolder>() {
    inner class ViewHolder(view : View) : RecyclerView.ViewHolder(view){
        val placecName = view.findViewById<TextView>(R.id.placeName)
        val placeAddress = view.findViewById<TextView>(R.id.placeAddress)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.place_item, parent, false)

        val holder = ViewHolder(view)

        holder.itemView.setOnClickListener{
            val position = holder.bindingAdapterPosition

            val place = placeList[position]

            val activity = fragment.activity

            if (activity is WeatherActivity){
                Log.d("哪一个", "第一个")
                activity.drawerLayout.closeDrawers()

                activity.viewModel.locationId = place.id

                activity.viewModel.placeName = place.name

                activity.refreshWeather()
            }else{
                Log.d("哪一个", "二个")
                val intent = Intent(parent.context, WeatherActivity::class.java).apply {
                    putExtra("locationId", place.id)
                    putExtra("placeName", place.name)
                }

                fragment.startActivity(intent)
                fragment.activity?.finish()
            }

            fragment.viewModel.savePlace(place)
        }

        return holder
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val place = placeList[position]
        val address = "${place.country} ${place.adm1} ${place.adm2}"

        holder.placecName.text = place.name
        holder.placeAddress.text = address
    }

    override fun getItemCount() = placeList.size
}